package cn.cosmosx.base.helper;

import cn.cosmosx.base.security.entity.SecurityUserVo;
import cn.cosmosx.base.constant.ResultCode;
import cn.cosmosx.base.exception.PlatformException;

/**
 * Session帮助
 */
public abstract class SessionHelper {
    private static final ThreadLocal<SecurityUserVo> CACHE = new ThreadLocal<>();

    /**
     * 获取当前用户
     */
    public static SecurityUserVo getUser() {
        SecurityUserVo user;
        try {
            user = CACHE.get();
        } catch (Exception e) {
            throw new PlatformException(ResultCode.U00000);
        }
        if (user == null) {
            throw new PlatformException(ResultCode.U90002);
        }
        return user;
    }

    /**
     * 获取用户id
     */
    public static Long getUserId() {
        return getUser().getUserId();
    }

    /**
     * 获取用户名
     */
    public static String getUserName() {
        return getUser().getUsername();
    }

    public static void put(SecurityUserVo session) {
        session.setPassword("");
        CACHE.set(session);
    }

    public static void clear() {
        CACHE.remove();
    }
}